<?php

namespace App\Http\Controllers\ZHIHU\Centers;

use Config;
use Response;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Eloqumd\Zhihu\ZhihuQuestion;
use App\Eloqumd\Zhihu\ZhihuSystemNotice;
use App\Eloqumd\Zhihu\ZhihuSystemAdv;
use App\Eloqumd\Zhihu\ZhihuFriendLink;
use App\Eloqumd\Zhihu\ZhihuSystemCover;
use App\Eloqumd\Zhihu\ZhihuTopic;
use App\Eloqumd\Zhihu\ZhihuUser;
use App\Eloqumd\Zhihu\ZhihuFavouriteQuestion;
use App\Eloqumd\Zhihu\ZhihuFollowerQuestion;
use App\Eloqumd\Zhihu\ZhihuCollection;
use App\Http\Controllers\ZHIHU\Systems\SystemsConfigController as SCC;
use App\Jobs\SPUV;

class MainWebSiteController extends Controller
{
    public function __construct()
    {
        // 网站统计
        $job = (new SPUV('zhihu'))->delay(1);
        $this->dispatch($job);
    }

    // 获取友情链接
    public function getWebFriendLinks(Request $request)
    {
        $currentTime = time();

        $listData = ZhihuFriendLink::where('status', 1)
            ->where('enddate', 0)
            ->orWhere('enddate', '>', $currentTime)
            ->get()
            ->toArray();

        return Response::json(['code' => 10000, 'message' => '', 'data' => $listData]);
    }

    // 获取精华榜列表
    public function getTopicCreamList(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = (int)$request->input('limit', 10);
        $offest = ($page - 1) * $limit;
        $user_id = (int)$request->input('user_id', 0);

        $where = null;
        $where['status'] = 1;
        $where['is_cream'] = 1;
        if ($user_id == 0) {
            $where['is_guest_view'] = 1;
        }

        $totalCount = ZhihuQuestion::where($where)->count();
        $listData = ZhihuQuestion::where($where)
            ->offset($offest)
            ->limit($limit)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $user = ZhihuUser::find($v['user_id']);
            $topic = ZhihuTopic::find($v['topic_id']);
            $cate = Config::get('api.zhihu_question_type')[$v['cates']];
            $listData[$k]['catesShow'] = $cate;
            $listData[$k]['lead'] = $v['lead'] == '' ? trans('zhihu.Question-Lead', [
                'title' => $v['title'],
                'username' => $user->nickname,
                'time' => $v['created_at']
            ]) : $v['lead'];
            $listData[$k]['body'] = Str::limit($v['content'], 100, '...');
            // $listData[$k]['body'] = $v['content'];
            $listData[$k]['meta'] = $user->nickname . ' / ' . $topic->name . ' / ' . $cate . ' / ' . $v['created_at'];
            $listData[$k]['username'] = $user->nickname;
            $listData[$k]['avatar'] = $user->avatar;
            $listData[$k]['topicname'] = $topic->name;
            $listData[$k]['viewBtnNameDetail'] = trans('zhihu.Question-View-Button-Name-Deatil');
            $listData[$k]['viewBtnNameClose'] = trans('zhihu.Question-View-Button-Name-Close');
            $listData[$k]['viewReadTag'] = 1;
            // 高亮处理
            if ($user_id == 0) {
                $listData[$k]['has_followers'] = 0;
                $listData[$k]['has_favourite'] = 0;
            } else {
                $listData[$k]['has_followers'] = (int)ZhihuFollowerQuestion::where('question_id', $v['id'])->where('user_id', $user_id)->value('status');
                $listData[$k]['has_favourite'] = (int)ZhihuFavouriteQuestion::where('question_id', $v['id'])->where('user_id', $user_id)->value('status');
            }

            if ($v['cates'] == 'blog') {
                $collection_count = ZhihuCollection::where('question_id', $v['id'])->where('status', 1)->count();
                $listData[$k]['collection_count'] = $collection_count;
                if ($user_id == 0) {
                    $listData[$k]['has_collection'] = 0;
                } else {
                    $listData[$k]['has_collection'] = (int)ZhihuCollection::where('question_id', $v['id'])->where('user_id', $user_id)->value('status');
                }
            }
        }

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return Response::json(['code' => 10000, 'message' => '', 'data' => $jsonData]);
    }

    // 获取话题问题列表
    public function getTopicListData(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = (int)$request->input('limit', 10);
        $offest = ($page - 1) * $limit;
        $user_id = (int)$request->input('user_id', 0);
        $topic_id = (int)$request->input('topic_id', 0);

        $where = null;
        $where['status'] = 1;
        $where['topic_id'] = $topic_id;
        if ($user_id == 0) {
            $where['is_guest_view'] = 1;
        }
        $topic = ZhihuTopic::find($topic_id);

        $totalCount = ZhihuQuestion::where($where)->count();
        $listData = ZhihuQuestion::where($where)
            ->offset($offest)
            ->limit($limit)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $user = ZhihuUser::find($v['user_id']);
            $cate = Config::get('api.zhihu_question_type')[$v['cates']];
            $listData[$k]['catesShow'] = $cate;
            $listData[$k]['leadOrigin'] = $v['lead'];
            $listData[$k]['lead'] = $v['lead'] == '' ? trans('zhihu.Question-Lead', [
                'title' => $v['title'],
                'username' => $user->nickname,
                'time' => $v['created_at']
            ]) : $v['lead'];
            $listData[$k]['body'] = $v['content'];
            // $listData[$k]['body'] = Str::limit($v['content'], 100, '...');
            $listData[$k]['meta'] = $user->nickname . ' / ' . $topic->name . ' / ' . $cate . ' / ' . $v['created_at'];
            $listData[$k]['username'] = $user->nickname;
            $listData[$k]['avatar'] = $user->avatar;
            $listData[$k]['timeShow'] = time_trans($v['created_at']);

            $star = $v['followers_count'] + $v['answers_count'] + $v['favourite_count'];
            if ($v['cates'] == 'blog') {
                $collection_count = (int)ZhihuCollection::where('question_id', $v['id'])->where('status', 1)->count();
                $star += $collection_count;
                $listData[$k]['starTips'] = '关注 ' . $v['followers_count'] . ' + 评论 ' . $v['answers_count'] . ' + 喜欢 ' . $v['favourite_count'] . ' + 收藏 ' . $collection_count . ' / ' . $v['created_at'];
            } else {
                $listData[$k]['starTips'] = '关注 ' . $v['followers_count'] . ' + 评论 ' . $v['answers_count'] . ' + 喜欢 ' . $v['favourite_count'] . ' / ' . $v['created_at'];
            }
            $listData[$k]['show'] = 0;
            $listData[$k]['star'] = $star;
        }

        $jsonData = ['list' => $listData, 'count' => $totalCount, 'title' => $topic->name];

        return Response::json(['code' => 10000, 'message' => '', 'data' => $jsonData]);
    }

    // 获取最新问题列表
    public function getWebLatestQuestion(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = (int)$request->input('limit', 10);
        $offest = ($page - 1) * $limit;
        $user_id = (int)$request->input('user_id', 0);

        $where = null;
        $where['status'] = 1;
        if ($user_id == 0) {
            $where['is_guest_view'] = 1;
        }

        $totalCount = ZhihuQuestion::where($where)->count();
        $listData = ZhihuQuestion::where($where)
            ->offset($offest)
            ->limit($limit)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $user = ZhihuUser::find($v['user_id']);
            $topic = ZhihuTopic::find($v['topic_id']);
            $cate = Config::get('api.zhihu_question_type')[$v['cates']];
            $listData[$k]['catesShow'] = $cate;
            $listData[$k]['lead'] = $v['lead'] == '' ? trans('zhihu.Question-Lead', [
                'title' => $v['title'],
                'username' => $user->nickname,
                'time' => $v['created_at']
            ]) : $v['lead'];
            $listData[$k]['body'] = Str::limit($v['content'], 100, '...');
            // $listData[$k]['body'] = $v['content'];
            $listData[$k]['meta'] = $user->nickname . ' / ' . $topic->name . ' / ' . $cate . ' / ' . $v['created_at'];
            $listData[$k]['username'] = $user->nickname;
            $listData[$k]['avatar'] = $user->avatar;
            $listData[$k]['topicname'] = $topic->name;
            $listData[$k]['viewBtnNameDetail'] = trans('zhihu.Question-View-Button-Name-Deatil');
            $listData[$k]['viewBtnNameClose'] = trans('zhihu.Question-View-Button-Name-Close');
            $listData[$k]['viewReadTag'] = 1;
            // 高亮处理
            if ($user_id == 0) {
                $listData[$k]['has_followers'] = 0;
                $listData[$k]['has_favourite'] = 0;
            } else {
                $listData[$k]['has_followers'] = (int)ZhihuFollowerQuestion::where('question_id', $v['id'])->where('user_id', $user_id)->value('status');
                $listData[$k]['has_favourite'] = (int)ZhihuFavouriteQuestion::where('question_id', $v['id'])->where('user_id', $user_id)->value('status');
            }

            if ($v['cates'] == 'blog') {
                $collection_count = ZhihuCollection::where('question_id', $v['id'])->where('status', 1)->count();
                $listData[$k]['collection_count'] = $collection_count;
                if ($user_id == 0) {
                    $listData[$k]['has_collection'] = 0;
                } else {
                    $listData[$k]['has_collection'] = (int)ZhihuCollection::where('question_id', $v['id'])->where('user_id', $user_id)->value('status');
                }
            }
        }

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return Response::json(['code' => 10000, 'message' => '', 'data' => $jsonData]);
    }

    // 获取最热问题列表
    public function getWebHotQuestion(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = (int)$request->input('limit', 10);
        $offest = ($page - 1) * $limit;
        $user_id = (int)$request->input('user_id', 0);

        $where = null;
        $where['status'] = 1;
        if ($user_id == 0) {
            $where['is_guest_view'] = 1;
        }

        $totalCount = ZhihuQuestion::where($where)->count();
        $listData = ZhihuQuestion::where($where)
            ->orderBy('favourite_count', 'desc')
            ->orderBy('answers_count', 'desc')
            ->orderBy('followers_count', 'desc')
            ->orderBy('read_count', 'desc')
            ->offset($offest)
            ->limit($limit)
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $user = ZhihuUser::find($v['user_id']);
            $topic = ZhihuTopic::find($v['topic_id']);
            $cate = Config::get('api.zhihu_question_type')[$v['cates']];
            $listData[$k]['catesShow'] = $cate;
            $listData[$k]['lead'] = $v['lead'] == '' ? trans('zhihu.Question-Lead', [
                'title' => $v['title'],
                'username' => $user->nickname,
                'time' => $v['created_at']
            ]) : $v['lead'];
            $listData[$k]['body'] = Str::limit($v['content'], 100, '...');
            // $listData[$k]['body'] = $v['content'];
            $listData[$k]['meta'] = $user->nickname . ' / ' . $topic->name . ' / ' . $cate . ' / ' . $v['created_at'];
            $listData[$k]['username'] = $user->nickname;
            $listData[$k]['avatar'] = $user->avatar;
            $listData[$k]['topicname'] = $topic->name;
            $listData[$k]['viewBtnNameDetail'] = trans('zhihu.Question-View-Button-Name-Deatil');
            $listData[$k]['viewBtnNameClose'] = trans('zhihu.Question-View-Button-Name-Close');
            $listData[$k]['viewReadTag'] = 1;
            // 高亮处理
            if ($user_id == 0) {
                $listData[$k]['has_followers'] = 0;
                $listData[$k]['has_favourite'] = 0;
            } else {
                $listData[$k]['has_followers'] = (int)ZhihuFollowerQuestion::where('question_id', $v['id'])->where('user_id', $user_id)->value('status');
                $listData[$k]['has_favourite'] = (int)ZhihuFavouriteQuestion::where('question_id', $v['id'])->where('user_id', $user_id)->value('status');
            }

            if ($v['cates'] == 'blog') {
                $collection_count = ZhihuCollection::where('question_id', $v['id'])->where('status', 1)->count();
                $listData[$k]['collection_count'] = $collection_count;
                if ($user_id == 0) {
                    $listData[$k]['has_collection'] = 0;
                } else {
                    $listData[$k]['has_collection'] = (int)ZhihuCollection::where('question_id', $v['id'])->where('user_id', $user_id)->value('status');
                }
            }
        }

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return Response::json(['code' => 10000, 'message' => '', 'data' => $jsonData]);
    }

    // 获取我关注的问题列表
    public function getFollowerQuestionList(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = (int)$request->input('limit', 10);
        $offest = ($page - 1) * $limit;
        $user_id = (int)$request->input('user_id', 0);

        $where = null;
        $where['flr.status'] = 1;
        if ($user_id == 0) {
            $where['qst.is_guest_view'] = 1;
        } else {
            $where['flr.user_id'] = $user_id;
        }

        $totalCount = ZhihuFollowerQuestion::from('zhihu_follower_questions as flr')
            ->leftJoin('zhihu_questions as qst', 'flr.question_id', '=', 'qst.id')
            ->where($where)
            ->where('qst.status', 1)
            ->count();
        $listData = ZhihuFollowerQuestion::from('zhihu_follower_questions as flr')
            ->select('qst.*')
            ->leftJoin('zhihu_questions as qst', 'flr.question_id', '=', 'qst.id')
            ->where($where)
            ->where('qst.status', 1)
            ->offset($offest)
            ->limit($limit)
            ->orderBy('flr.created_at', 'desc')
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $user = ZhihuUser::find($v['user_id']);
            $topic = ZhihuTopic::find($v['topic_id']);
            $cate = Config::get('api.zhihu_question_type')[$v['cates']];
            $listData[$k]['catesShow'] = $cate;
            $listData[$k]['lead'] = $v['lead'] == '' ? trans('zhihu.Question-Lead', [
                'title' => $v['title'],
                'username' => $user->nickname,
                'time' => $v['created_at']
            ]) : $v['lead'];
            $listData[$k]['body'] = Str::limit($v['content'], 100, '...');
            // $listData[$k]['body'] = $v['content'];
            $listData[$k]['meta'] = $user->nickname . ' / ' . $topic->name . ' / ' . $cate . ' / ' . $v['created_at'];
            $listData[$k]['username'] = $user->nickname;
            $listData[$k]['avatar'] = $user->avatar;
            $listData[$k]['topicname'] = $topic->name;
            $listData[$k]['viewBtnNameDetail'] = trans('zhihu.Question-View-Button-Name-Deatil');
            $listData[$k]['viewBtnNameClose'] = trans('zhihu.Question-View-Button-Name-Close');
            $listData[$k]['viewReadTag'] = 1;
            // 高亮处理
            if ($user_id == 0) {
                $listData[$k]['has_followers'] = 0;
                $listData[$k]['has_favourite'] = 0;
            } else {
                $listData[$k]['has_followers'] = (int)ZhihuFollowerQuestion::where('question_id', $v['id'])->where('user_id', $user_id)->value('status');
                // $listData[$k]['has_followers'] = 1;
                $listData[$k]['has_favourite'] = (int)ZhihuFavouriteQuestion::where('question_id', $v['id'])->where('user_id', $user_id)->value('status');
            }

            if ($v['cates'] == 'blog') {
                $collection_count = ZhihuCollection::where('question_id', $v['id'])->where('status', 1)->count();
                $listData[$k]['collection_count'] = $collection_count;
                if ($user_id == 0) {
                    $listData[$k]['has_collection'] = 0;
                } else {
                    $listData[$k]['has_collection'] = (int)ZhihuCollection::where('question_id', $v['id'])->where('user_id', $user_id)->value('status');
                }
            }
        }

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return Response::json(['code' => 10000, 'message' => '', 'data' => $jsonData]);
    }

    // 获取博文中心问题列表
    public function getBlogQuestionList(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = (int)$request->input('limit', 10);
        $offest = ($page - 1) * $limit;
        $user_id = (int)$request->input('user_id', 0);

        $where = null;
        $where['status'] = 1;
        $where['cates'] = 'blog';
        if ($user_id == 0) {
            $where['is_guest_view'] = 1;
        }

        $totalCount = ZhihuQuestion::where($where)->count();
        $listData = ZhihuQuestion::where($where)
            ->orderBy('favourite_count', 'desc')
            ->orderBy('answers_count', 'desc')
            ->orderBy('followers_count', 'desc')
            ->orderBy('read_count', 'desc')
            ->offset($offest)
            ->limit($limit)
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $user = ZhihuUser::find($v['user_id']);
            $topic = ZhihuTopic::find($v['topic_id']);
            $cate = Config::get('api.zhihu_question_type')[$v['cates']];
            $listData[$k]['catesShow'] = $cate;
            $listData[$k]['lead'] = $v['lead'] == '' ? trans('zhihu.Question-Lead', [
                'title' => $v['title'],
                'username' => $user->nickname,
                'time' => $v['created_at']
            ]) : $v['lead'];
            $listData[$k]['body'] = Str::limit($v['content'], 100, '...');
            // $listData[$k]['body'] = $v['content'];
            $listData[$k]['meta'] = $user->nickname . ' / ' . $topic->name . ' / ' . $cate . ' / ' . $v['created_at'];
            $listData[$k]['username'] = $user->nickname;
            $listData[$k]['avatar'] = $user->avatar;
            $listData[$k]['topicname'] = $topic->name;
            $listData[$k]['viewBtnNameDetail'] = trans('zhihu.Question-View-Button-Name-Deatil');
            $listData[$k]['viewBtnNameClose'] = trans('zhihu.Question-View-Button-Name-Close');
            $listData[$k]['viewReadTag'] = 1;
            // 高亮处理
            if ($user_id == 0) {
                $listData[$k]['has_followers'] = 0;
                $listData[$k]['has_favourite'] = 0;
            } else {
                $listData[$k]['has_followers'] = (int)ZhihuFollowerQuestion::where('question_id', $v['id'])->where('user_id', $user_id)->value('status');
                $listData[$k]['has_favourite'] = (int)ZhihuFavouriteQuestion::where('question_id', $v['id'])->where('user_id', $user_id)->value('status');
            }

            // if ($v['cates'] == 'blog') {
            $collection_count = ZhihuCollection::where('question_id', $v['id'])->where('status', 1)->count();
            $listData[$k]['collection_count'] = $collection_count;
            if ($user_id == 0) {
                $listData[$k]['has_collection'] = 0;
            } else {
                $listData[$k]['has_collection'] = (int)ZhihuCollection::where('question_id', $v['id'])->where('user_id', $user_id)->value('status');
            }
            // }
        }

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return Response::json(['code' => 10000, 'message' => '', 'data' => $jsonData]);
    }

    // 查看问题统计阅读
    public function viewShowQuestion(Request $request)
    {
        $question_id = (int)$request->input('question_id', 0);
        $user_id = (int)$request->input('user_id', 0);

        if ($user_id == 0) {
            $user_id = 'U' . ip2long(request()->getClientIp());
        }

        $key = 'VIEWQSS_' . $user_id . '_' . $question_id;
        $tag = 0;
        if (Redis::setnx($key, $key)) {
            $tag = 1;
            Redis::setex($key, Config::get('api.zhihu_question_read'), $key);

            $question = ZhihuQuestion::find($question_id);
            $question->read_count = $question->read_count + 1;
            $question->save();
        }

        return Response::json(['code' => 10000, 'message' => '', 'data' => ['hasread' => $tag]]);
    }

    // 获取最新公告信息
    public function getWebLatestNotice(Request $request)
    {
        $content = ZhihuSystemNotice::where('status', 1)->value('content');

        return Response::json(['code' => 10000, 'message' => '', 'data' => ['notice' => $content]]);
    }

    // 获取广告信息
    public function getWebAdvs(Request $request)
    {
        $type = $request->input('type', '');
        $limit = SCC::getting('advs')[$type] ?? 0;
        $currentTime = time();

        $advListData = ZhihuSystemAdv::where('type', $type)
            ->where('status', 1)
            ->where('start_date', '<=', $currentTime)
            ->where('end_date', '>', $currentTime)
            ->limit($limit)
            ->get()
            ->toArray();

        return Response::json(['code' => 10000, 'message' => '', 'data' => $advListData]);
    }

    // 获取封面信息
    public function getWebCover(Request $request)
    {
        $currentTime = time();
        $special = ZhihuSystemCover::where('start_date', '<=', $currentTime)->where('end_date', '>=', $currentTime)->limit(1)->first();
        if ($special) {
            return Response::json(['code' => 10000, 'message' => '', 'data' => ['coverimg' => $special['coverimg']]]);
        }

        $common = ZhihuSystemCover::where('status', 1)->limit(1)->first();

        $coverimg = $common['coverimg'] ?? '';

        return Response::json(['code' => 10000, 'message' => '', 'data' => ['coverimg' => $coverimg]]);
    }

    // 获取话题统计信息
    public function getWebTopics(Request $request)
    {
        $jsonData = ZhihuTopic::where('status', 1)->get()->toArray();
        foreach ($jsonData as $k => $v) {
            $jsonData[$k]['title'] = $v['name'];
            $jsonData[$k]['count'] = $v['questions_count'] > 999999 ? number_format(999999) . '+' : number_format($v['questions_count']);
            if ($v['questions_count']) {
                $jsonData[$k]['href'] = "/#/topic/" . $v['id'];
            }
        }

        return Response::json(['code' => 10000, 'message' => '', 'data' => $jsonData]);
    }

    // 获取有效话题
    public function getWebTopicsEffect(Request $request)
    {
        $jsonData = ZhihuTopic::where('status', 1)->where('questions_count', '>', 0)->get()->toArray();
        foreach ($jsonData as $k => $v) {
            $jsonData[$k]['count'] = $v['questions_count'] > 999999 ? number_format(999999) . '+' : number_format($v['questions_count']);
        }

        return Response::json(['code' => 10000, 'message' => '', 'data' => $jsonData]);
    }
}
